<template>
  <el-drawer
    title="答案列表"
    :visible.sync="drawerVisible"
    direction="rtl"
    size="80%"
    :with-header="false"
  >
    <div class="drawer-content">
      <el-divider content-position="left">基本信息</el-divider>

      <el-descriptions title="">
        <el-descriptions-item label="主题">{{
          register.theme
        }}</el-descriptions-item>
        <el-descriptions-item label="登记人">{{
          register.userName
        }}</el-descriptions-item>
        <el-descriptions-item label="分类">
          <el-tag size="small">{{ register.typeName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="主题描述">
          {{
            register.remark && register.remark.length > 100
              ? register.remark.slice(0, 100) + "..."
              : register.remark
          }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 查询输入框和添加按钮 -->
      <el-divider content-position="left">答案列表</el-divider>
      <div class="search-and-button">
        <el-input
          v-model="search.keyword"
          placeholder="请输入关键字进行搜索"
          clearable
          @keyup.enter.native="getTableInfo()"
          @clear="getTableInfo()"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getTableInfo()"
          />
        </el-input>
        <div class="btnList">
          <el-button type="primary" icon="el-icon-plus" @click="showDialog()"
            >新建</el-button
          >
        </div>
      </div>

      <!-- 表格 -->
      <el-row class="table">
        <el-table
          ref="tableData"
          v-loading="loading"
          :data="tableData"
          stripe
          border
        >
          <el-table-column align="center" type="index" label="索引" />
          <el-table-column prop="answer" align="center" label="经验回复">
            <template #default="{ row }">
              <!-- 使用 el-popover 实现鼠标悬停预览 -->
              <el-popover trigger="hover" placement="top" width="800">
                <!-- 预览内容 -->
                <p>{{ row.answer }}</p>
                <!-- 复制按钮 -->
                <el-button type="text" @click="copyAnswer(row.answer)"
                  >复制</el-button
                >

                <!-- 悬停的触发内容, 隐藏显示部分 -->
                <span slot="reference" style="cursor: pointer">
                  {{
                    row.answer && row.answer.length > 50
                      ? row.answer.slice(0, 50) + "..."
                      : row.answer
                  }}
                </span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            prop="industry"
            align="center"
            label="所属行业"
            width="120px"
          />
          <el-table-column
            prop="userName"
            align="center"
            label="登记人"
            width="100px"
          />
          <el-table-column
            prop="registerTime"
            align="center"
            label="登记时间"
            width="180px"
          />
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="120px"
          >
            <template #default="{ row }">
              <el-button-group>
                <!-- <el-button type="text" @click="showDialog(row)">
                  <i class="iconfont icon-search"></i>
                </el-button> -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showDialog(row)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteRow(row)"
                ></el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row width="100%">
        <pagination
          ref="Pagination"
          :total="total"
          :current.sync="search.current"
          :size.sync="search.size"
          @pagination="getTableInfo"
        />
      </el-row>
    </div>
    <el-dialog
      v-dialogDrag
      :visible.sync="dialogVisible"
      :title="title"
      width="850px"
      :append-to-body="true"
      @close="resetForm('ruleForm')"
    >
      <button-group
        ref="buttonGroup"
        @submitForm="submitForm('ruleForm')"
        @cancel="dialogVisible = false"
      />
      <div class="formTopFont">答案登记</div>
      <el-row>
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="创建人" prop="userName">
                <el-input
                  v-model="ruleForm.userName"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="行业" prop="industry">
                <el-input
                  v-model="ruleForm.industry"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="回答" prop="answer">
              <el-input
                type="textarea"
                rows="20"
                v-model="ruleForm.answer"
                show-word-limit
              />
            </el-form-item>
          </el-row>
        </el-form>
      </el-row>
    </el-dialog>
  </el-drawer>
</template>
<script>
import Pagination from "@/components/Pagination";

export default {
  components: {
    Pagination,
  },
  props: {
    //   // 定义一个 props 来接收父组件的数据
    //   tid: {
    //     type: String, // 这里可以根据传递的数据类型调整类型 (String, Number, Object, Array, etc.)
    //     required: true, // 如果是必须传递的，可以设置为 true
    //   },
  },
  data() {
    const params = {
      isShow: "",
      dataName: "",
      sort: "",
    };
    return {
      search: {
        id: 0,
        current: 1,
        size: 20,
        keyword: "",
        treeStr: "-1",
      },
      register: {},
      title: "",
      loading: false,
      tableData: [],
      total: 0,

      ruleForm: {
        registerId: "",
        answer: "",
        userName: "",
        industry: "",
      },
      rules: {
        theme: [{ required: true, message: "主题不能为空", trigger: "blur" }],
        typeName: [
          { required: true, message: "分类不能为空", trigger: "blur" },
        ],
        // supplierCode: [
        //   { required: true, message: "供应商编号不能为空！", trigger: "blur" },
        //   { validator: checkSupplierCode, trigger: "blur" },
        // ],
      },
      drawerVisible: false,
      dialogVisible: false,
      departData: [],
      basicParams: params,
    };
  },
  watch: {},
  mounted() {},
  methods: {
    /**
     * @description: page
     * @param {*} page
     * @return {*}
     */
    async getTableInfo(page = 1) {
      this.search.current = page;
      this.search.id = this.tid;
      this.loading = true;
      const res = await this.$axios.post(
        "/data/register/answerDetail",
        this.search
      );
      if (res?.data.code === 200) {
        this.tableData = res.data.data.list;
        this.total = res.data.data.total;
        setTimeout(() => {
          this.loading = false;
        }, 100);
      } else {
        this.loading = false;
      }
    },
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    // 显示对话框，区分编辑和新增
    showDialog(row = null) {
      if (row) {
        // 编辑模式，填充表单
        this.title = "编辑信息";
        this.ruleForm = { ...row }; // 将 row 数据赋值到表单
      } else {
        // 新建模式，清空表单
        this.title = "新建信息";
        this.resetForm("ruleForm"); // 清空表单
      }
      this.dialogVisible = true; // 显示对话框
    },

    async showDrawer(row) {
      this.drawerVisible = true;
      if (row && row.hasOwnProperty("id")) {
        this.tid = row.id;
        this.register = row;
      }
      this.getTableInfo();
    },

    /**
     * @description: 删除当前行数据
     * @param {*} row
     * @return {*}
     */
    deleteRow(row) {
      this.$confirm(`确认删除当前答案？`, "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.delete(
            `/data/register/removeAnswer/${row.id}`
          );
          if (res.data.code === 200) {
            this.$notify.success("删除成功！");
            this.getTableInfo();
          } else {
            this.$notify.error(res.data.msg);
          }
        })
        .catch(() => {});
    },
    /**
     * @description: 表单提交
     * @param {*} formName
     * @return {*}
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.ruleForm.registerId = this.tid;
          const res = await this.$axios.post(
            "/data/register/saveOrUpdateAnswer",
            this.ruleForm
          );
          if (res?.data.code === 200) {
            this.$notify.success("提交成功！");
            this.dialogVisible = false;
            this.getTableInfo();
            this.$emit("getTreeData");
          } else {
            this.$notify.error(res.data.msg);
          }
        }
      });
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      // 检查是否有 formName 引用
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.ruleForm = {
        registerId: "",
        answer: "",
        userName: "",
        industry: "",
      };
    },

    // 预览功能，可以通过弹窗来展示
    previewAnswer(answer) {
      this.$alert(answer, "预览", {
        confirmButtonText: "确定",
      });
    },

    // 复制功能
    copyAnswer(answer) {
      const el = document.createElement("textarea");
      el.value = answer;
      document.body.appendChild(el);
      el.select();
      document.execCommand("copy");
      document.body.removeChild(el);
      this.$message.success("复制成功");
    },
  },
};
</script>
<style lang="scss" scoped>
.drawer-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 30px;
}
.search-and-button {
  line-height: 30px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  .el-input {
    width: 350px;
  }
}
.table {
  margin-top: 10px;
  width: 100%;
  height: 70%;
}
</style>
